package routers

import (
	"eat-every-day/global"
	"eat-every-day/internal/model"
	"eat-every-day/internal/routers/api"
	"eat-every-day/pkg/logs"
	"eat-every-day/pkg/setting"
	"github.com/gin-gonic/gin"
	"time"
)

func init() {
	err := setupSetting()
	if err != nil {
		logs.Log.Error("初始化配置文件失败：", err)
	}

	model.MySqlDataBase.Init(global.DatabaseSetting)
	model.InitRedis(global.RedisSetting)
	api.InitHandlers()
}

func Load(engine *gin.Engine, middlewares ...gin.HandlerFunc) *gin.Engine {

	gin.SetMode(global.ServerSetting.RunMode)
	engine.Use(gin.Recovery())
	engine.Use(middlewares...)

	loadUsersRouter(engine)

	return engine
}

func setupSetting() error {
	newSetting, err := setting.NewSetting()
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("App", &global.AppSetting)
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("Database", &global.DatabaseSetting)
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("JWT", &global.JWTSetting)
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("QiNiu", &global.QiNiuSetting)
	if err != nil {
		return err
	}

	err = newSetting.ReadSection("Redis", &global.RedisSetting)
	if err != nil {
		return err
	}

	global.ServerSetting.ReadTimeout *= time.Second
	global.ServerSetting.WriteTimeout *= time.Second
	global.JWTSetting.Expire *= time.Hour
	return nil
}
